/*
 * Copyright [2013-2021], Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.polardbx.executor.operator.util;

import com.alibaba.polardbx.executor.chunk.Block;
import com.alibaba.polardbx.executor.chunk.Chunk;
import com.alibaba.polardbx.executor.chunk.ChunkBuilder;

import java.util.List;

import static java.util.Objects.requireNonNull;

public class ChunkWithPosition {

    private final Chunk chunk;
    private final int position;

    public ChunkWithPosition(Chunk chunk, int position) {
        this.chunk = requireNonNull(chunk, "chunk is null");
        this.position = position;
    }

    public Chunk getChunk() {
        return chunk;
    }

    public int getPosition() {
        return position;
    }

    public Object getObject(int index) {
        return chunk.getBlock(index).getObject(position);
    }

    public void appendTo(ChunkBuilder chunkBuilder) {
        chunkBuilder.declarePosition();
        for (int i = 0; i < chunk.getBlockCount(); i++) {
            chunkBuilder.appendTo(chunk.getBlock(i), i, position);
        }
    }

    public void appendTo(ChunkBuilder chunkBuilder, List<Integer> outputChannels) {
        chunkBuilder.declarePosition();
        for (int i = 0; i < outputChannels.size(); i++) {
            Block block = chunk.getBlock(outputChannels.get(i));
            chunkBuilder.appendTo(block, i, position);
        }
    }
}
